package com.zbw.printlibrary.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zbw.printlibrary.R;
import com.zbw.printlibrary.adapter.PrintDeviceAdapter;
import com.zbw.printlibrary.bean.PrintUSBDevice;
import com.zbw.printlibrary.util.UsbController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 作者 ：Wesley
 * 时间 ：2021/12/14 18:14
 * 这个类是干嘛的？：PrintNewUsbActivity
 */
public class PrintNewUsbActivity extends AppCompatActivity {
    private RelativeLayout backRL;//返回
    private RecyclerView printRV;//USB列表
    private PrintDeviceAdapter mDeviceAdapter;
    List<PrintUSBDevice> devs;
    private UsbManager mUsbManager;
    private TextView no_data_tv;
    public UsbController usbCtrl;
    public UsbDevice dev;
    private int USB_VID;
    private int USB_PID;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏系统通知栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
        setContentView(R.layout.activity_new_print);
        setActivitySize();
        getUSBPram();
        initUI();
        initData();
    }


    private void initData() {
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> devMap = mUsbManager.getDeviceList();
        devs = new ArrayList<>();
        for (UsbDevice dev : devMap.values()) {
            if (dev.getInterfaceCount() > 0 &&  dev.getInterface(0).getInterfaceClass() == 7) {
                boolean old = false;
                if(USB_VID == dev.getVendorId()&&USB_PID ==dev.getProductId()){
                    old = true;
                    initPrint(USB_VID, USB_PID);
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    devs.add(new PrintUSBDevice(dev.getProductName(), dev, old));
                } else {
                    devs.add(new PrintUSBDevice(dev.getDeviceName(), dev, old));
                }
                Log.i("name",dev.getDeviceName());
            }
        }
        mDeviceAdapter.setNewData(devs);

        if(devs.size() == 0){
            no_data_tv.setVisibility(View.VISIBLE);
            printRV.setVisibility(View.GONE);
        }else{
            no_data_tv.setVisibility(View.GONE);
            printRV.setVisibility(View.VISIBLE);
        }
    }

    public void getUSBPram() {
        SharedPreferences share = this.getSharedPreferences("SHEZHI", MODE_PRIVATE);
        USB_PID = share.getInt("USB_PID", 0);
        USB_VID = share.getInt("USB_VID", 0);
    }

    private void initUI() {
        no_data_tv = findViewById(R.id.no_data_tv);
        backRL = findViewById(R.id.rela_back);
        backRL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        printRV = findViewById(R.id.print_rv);
        printRV.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mDeviceAdapter = new PrintDeviceAdapter();
        mDeviceAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                if(devs.get(position).isCheck()){
                    printStart();
                }else{
                    for (int i = 0; i < devs.size(); i++) {
                        devs.get(i).setCheck(false);
                    }
                    devs.get(position).setCheck(true);
                    mDeviceAdapter.notifyDataSetChanged();
                    UsbDevice device = devs.get(position).getDevice();
                    initPrint(device.getVendorId(), device.getProductId());
                }
            }
        });
        printRV.setAdapter(mDeviceAdapter);
    }

    /**
     * 动态设置Activity的大小。
     */
    private void setActivitySize() {
        //动态设置Activity的大小。
        Display display = getWindowManager().getDefaultDisplay(); // 为获取屏幕宽、高
        Window window = getWindow();
        WindowManager.LayoutParams windowLayoutParams = window.getAttributes(); // 获取对话框当前的参数值
        windowLayoutParams.width = (int) (display.getWidth() * 0.5); // 宽度设置为屏幕的0.7
        windowLayoutParams.height = (int) (display.getHeight() * 0.6); // 高度设置为屏幕的0.7
        windowLayoutParams.alpha = 1f;// 设置透明度
        getWindow().setAttributes(windowLayoutParams);
    }

    //选择
    private void initPrint(int vid, int pid) {
        usbCtrl = new UsbController(this, mHandler);
        dev = usbCtrl.getDev(vid, pid);
        if (dev != null) {
            if (!(usbCtrl.isHasPermission(dev))) {
                usbCtrl.getPermission(dev);
            }
            USB_VID = vid;
            USB_PID = pid;
            SaveData();
        }
    }

    private final Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            Log.i("USB连接回调",msg.toString());
        }
    };

    //保存数据
    public void SaveData() {
        //指定操作的文件名称
        SharedPreferences share = getSharedPreferences("SHEZHI", MODE_PRIVATE);
        SharedPreferences.Editor edit = share.edit(); //编辑文件
        edit.putInt("USB_VID", USB_VID);
        edit.putInt("USB_PID", USB_PID);
        edit.commit();  //保存数据信息
    }

    //测试打印
    private void printStart() {
        try{
            String msg = "";
            byte[] cmd = new byte[3];
            cmd[0] = 0x1b;
            cmd[1] = 0x21;
            cmd[2] |= 0x10;
            usbCtrl.sendByte(cmd, dev); // 倍宽、倍高模式
            usbCtrl.sendMsg("　　　　　　　智百威\n", "GBK", dev);
            cmd[2] &= 0xEF;
            usbCtrl.sendByte(cmd, dev); // 取消倍高、倍宽模式
            msg = "  您已经成功的连接上了usb打印机！\n\n" + " 你好 \n\n" + "   打印成功！  \n\n";
            usbCtrl.sendMsg(msg, "GBK", dev);
        }catch (Exception e){
            Toast.makeText(this,"请检测打印机是否可用！",Toast.LENGTH_SHORT).show();
        }
    }



}
